package com.lishe.lishe.asynchttp;

import android.content.Context;

import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.utils.LogUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.util.TextUtils;

/**
 * Created by zhcase on 2017/9/5.
 */

public class LSWebHelper {

    private static final String TAG = LSWebHelper.class.getSimpleName();

    public static String BASE_URL = Globals.LISHE_URL;//LISHE_URL   LISHE_URL_TEST

    private static LSWebHelper instance;

    private LSWebHelper() {
    }

    public static LSWebHelper getInstance() {

        if (instance == null) {
            synchronized (LSWebHelper.class) {
                if (instance == null) {
                    instance = new LSWebHelper();
                }
            }
        }
        return instance;
    }

    private Map<String, Object> getParams4Token(Map<String, Object> params) {
        if (params == null) {
            params = new HashMap<String, Object>();
        }
        String token = Globals.getToken();
        if (!TextUtils.isEmpty(token)) {
            params.put("token", token);
        }
        return params;
    }

    /**
     * 判断是否已登录
     *
     * @return
     */
    public boolean isUserLogined() {
        if (TextUtils.isEmpty(Globals.getToken())) {
            return false;
        } else {
            return true;
        }
    }

//    /**
//     * 判断是否已登录
//     *
//     * @return
//     */
//    public boolean isUserLogined(Context context) {
//        if (TextUtils.isEmpty(SharedPreferencesUtils.getPasswordSaved(context))) {
//            return false;
//        } else {
//            return true;
//        }
//    }


    /**
     * POST请求中自动加上token
     *
     * @param relativeUrl
     * @param params
     * @param callBack
     */
    public void postAsynUseToken(String relativeUrl, Map<String, Object> params, final WebCallBack callBack) {
        postAsyn(relativeUrl, getParams4Token(params), callBack);
    }

    /**
     * POST Asyn 初步处理
     *
     * @param relativeUrl
     * @param params
     * @param callBack
     */
    public void postAsyn(String relativeUrl, Map<String, Object> params, final WebCallBack callBack) {

        RequestParams paramsReq = new RequestParams();

        if (params != null && params.size() > 0) {
            for (String key : params.keySet()) {
                paramsReq.put(key, params.get(key));
            }

            LogUtil.e(TAG, params.toString() + "  " + paramsReq.toString());
        }


        HttpUtils.post(BASE_URL + relativeUrl, paramsReq, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String result = new String(responseBody);
                LogUtil.e(TAG, "onSuccess.result:" + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String msg = jsonObject.optString("msg");
                    String dataStr = jsonObject.optString("data");
                    int errcode = jsonObject.optInt("errcode", -1);
                    if (errcode == 100 || errcode == 0) {
                        JSONObject data = jsonObject.optJSONObject("data");
                        if (callBack != null) {
                            callBack.onSuccess(data, dataStr, msg);
                        }
                    } else {
                        if (callBack != null) {
                            if (msg == null) {
                                msg = "";
                            }
                            callBack.onFailure(msg);
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    if (callBack != null) {
                        callBack.onFailure("请求或参数错误！");
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

                if (callBack != null) {
                    callBack.onFailure("网络或服务器出错！");
                }
            }
        });
    }


    /**
     * GET请求中自动加上token
     *
     * @param relativeUrl
     * @param params
     * @param callBack
     */
    public void getAsynUseToken(String relativeUrl, Map<String, Object> params, final WebCallBack callBack) {
        getAsyn(relativeUrl, getParams4Token(params), callBack);
    }


    /**
     * GETs Asyn 初步处理
     *
     * @param relativeUrl
     * @param params
     * @param callBack
     */
    public void getAsyn(String relativeUrl, Map<String, Object> params, final WebCallBack callBack) {

        RequestParams paramsReq = new RequestParams();

        if (params != null && params.size() > 0) {
            for (String key : params.keySet()) {
                paramsReq.put(key, params.get(key));
            }
        }


        HttpUtils.get(BASE_URL + relativeUrl, paramsReq, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String result = new String(responseBody);
                //Log.e(TAG, "onSuccess.result:" + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String msg = jsonObject.optString("msg");
                    String dataStr = jsonObject.optString("data");
                    int errcode = jsonObject.optInt("errcode", -1);
                    if (errcode == 100 || errcode == 0) {
                        JSONObject data = jsonObject.optJSONObject("data");
                        if (callBack != null) {
                            callBack.onSuccess(data, dataStr, msg);
                        }
                    } else {
                        if (callBack != null) {
                            if (msg == null) {
                                msg = "";
                            }
                            callBack.onFailure(msg);
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    if (callBack != null) {
                        callBack.onFailure("请求或参数错误！");
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {


                if (callBack != null) {
                    callBack.onFailure("网络或服务器出错！");
                }
            }
        });
    }


    /**
     * POST请求上传文件或图片
     *
     * @param relativeUrl
     * @param params
     * @param callBack
     */
    public void postSynUploadFileUseToken(Context ctx, String relativeUrl, Map<String, Object> params, Map<String, File> fileParams, final WebUpLoadFileCallBack callBack) {

        //File file = new File(path);
        //if (file.exists() && file.length() > 0) {


        RequestParams paramsReq = new RequestParams();

        paramsReq.put("token", Globals.getToken());

        if (params != null && params.size() > 0) {
            for (String key : params.keySet()) {
                paramsReq.put(key, params.get(key));
            }
        }
        if (fileParams != null && fileParams.size() > 0) {
            for (String key : fileParams.keySet()) {
                try {
                    paramsReq.put(key, fileParams.get(key));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

            }
        }


        AsyncHttpResponseHandler asyncHttpResponseHandler = new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  byte[] responseBody) {

                String result = new String(responseBody);
                LogUtil.i(TAG, "onSuccess.result:" + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String msg = jsonObject.optString("msg");
                    String dataStr = jsonObject.optString("data");
                    int errcode = jsonObject.optInt("errcode", -1);
                    if (errcode == 100 || errcode == 0) {
                        JSONObject data = jsonObject.optJSONObject("data");
                        if (callBack != null) {
                            callBack.onSuccess(data, dataStr, msg);
                        }
                    } else {
                        if (callBack != null) {
                            if (msg == null) {
                                msg = "";
                            }
                            callBack.onFailure(msg);
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    if (callBack != null) {
                        callBack.onFailure("请求或参数错误！");
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  byte[] responseBody, Throwable error) {
                // 上传失败后要做到工作
                if (callBack != null) {
                    callBack.onFailure("网络或服务器出错！");
                }
            }

            @Override
            public void onProgress(long bytesWritten, long totalSize) {
                // TODO Auto-generated method stub
                super.onProgress(bytesWritten, totalSize);
                LogUtil.e(TAG, "bytesWritten---" + bytesWritten);
                LogUtil.e(TAG, "totalSize---" + totalSize);
                int count = (int) (((double) bytesWritten / (double) totalSize) * 100);
                // 上传进度显示
                //progress.setProgress(count);
                LogUtil.e("上传 Progress>>>>>", bytesWritten + " / " + totalSize);
                if (callBack != null) {
                    callBack.onProgress(count);
                }
            }


            @Override
            public void onRetry(int retryNo) {
                super.onRetry(retryNo);
            }

        };


        HttpUtils.post(BASE_URL + relativeUrl, paramsReq, asyncHttpResponseHandler);
    }


//    public String getToken() {
//        return token;
//    }
//
//    public void setToken(String t) {
//        token = t;
//    }


    public interface WebCallBack {
        public void onSuccess(JSONObject dataJson, String dataString, String message);


        public void onFailure(String message);
    }

    public interface WebUpLoadFileCallBack {

        public void onSuccess(JSONObject dataJson, String dataString, String message);


        public void onFailure(String message);


        public void onProgress(int count);

    }

}
